package com.mrdeer.security;

import cn.hutool.core.util.StrUtil;
import com.mrdeer.common.entity.sys.User;
import com.mrdeer.common.exception.BusinessException;
import com.mrdeer.common.tools.NameUtil;
import com.mrdeer.common.tools.RedisTemplateHelper;
import com.mrdeer.web.service.sys.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private RedisTemplateHelper redisTemplate;

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String flagKey = "loginFailFlag:" + s;
        String value = redisTemplate.get(flagKey);
        Long timeRest = redisTemplate.getExpire(flagKey, TimeUnit.MINUTES);
        if (StrUtil.isNotBlank(value)) {
            //超过限制次数
            throw new BusinessException("登录错误次数超过次数限制，请" + timeRest + "分钟后再试");
        }
        User user;
        if (NameUtil.mobile(s)) {
            user = sysUserService.findByMobile(s);
        } else if (NameUtil.email(s)) {
            user = sysUserService.findByEmail(s);
        } else {
            user = sysUserService.findByUsername(s);
        }
        return new SecurityUserDetails(user);
    }
}
